//
//  YWSelectBuildingApartmentTVC.m
//  maintain
//
//  Created by 烟雨云渊 on 2017/5/24.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWSelectBuildingApartmentTVC.h"
#import "YWSelectBuildingTableViewController.h"
#import "YWSelectApartmentTableViewController.h"

#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "YWLoginTool.h"

#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWApartment.h"

@interface YWSelectBuildingApartmentTVC ()
<YWSelectBuildingTableViewControllerDelegate,YWSelectApartmentTableViewControllerDelegate>{
    YWBuilding *currentBuilding;
    YWApartment *currentApartment;
}
@property (nonatomic, strong) NSArray *allBuildings;
@end

@implementation YWSelectBuildingApartmentTVC

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"选择位置";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(clickRightBarButton:)];
    [self initTableView];
}

- (void)initTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.rowHeight = 44.0f;
}

- (NSArray *)allBuildings{
    if (!_allBuildings) {
        _allBuildings = [[YWBuildingManager shareManager] allBuilding];
    }
    return _allBuildings;
}

- (NSArray *)allApartments{
    NSArray *allApartments = nil;
    allApartments = [[NSArray alloc] initWithArray:[[YWBuildingManager shareManager] apartmentWithbuildingId:currentBuilding.buildingId]];
    return allApartments;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuseIdentifier = @"YWSelectBuildingApartmentTVCReuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        cell.textLabel.font = kContentFont;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    [self configureCell:cell withIndexPath:indexPath];
    return cell;
}

- (void)configureCell:(UITableViewCell*)cell withIndexPath:(NSIndexPath*)indexPath{
    if (indexPath.section == 0) {
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        buildingShowName = buildingShowName.length ? buildingShowName:@"楼盘";
        cell.textLabel.text = currentBuilding.buildingName.length ? currentBuilding.buildingName : [NSString stringWithFormat:@"选择%@",buildingShowName];
    }else if (indexPath.section ==1){
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        apartmentShowName = apartmentShowName.length ? apartmentShowName:@"楼栋";
        cell.textLabel.text = currentApartment.apartmentName.length ? currentApartment.apartmentName : [NSString stringWithFormat:@"选择%@",apartmentShowName];
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWSelectBuildingApartmentTVCForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        return buildingShowName.length?[NSString stringWithFormat:@"选择%@",buildingShowName]:@"选择楼盘";
    }else if (section == 1) {
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        return apartmentShowName.length?[NSString stringWithFormat:@"选择%@",apartmentShowName]:@"选择楼栋";
    }else{
        return @"无";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YWSelectBuildingTableViewController *selectBuildingVC = [[YWSelectBuildingTableViewController alloc] init];
        selectBuildingVC.delegate = self;
        selectBuildingVC.ownBuilding = currentBuilding;
        [self.navigationController pushViewController:selectBuildingVC animated:YES];
    }else if (indexPath.section == 1){
        if (currentBuilding.buildingName.length) {
            YWSelectApartmentTableViewController *selectApartmentVC = [[YWSelectApartmentTableViewController alloc] init];
            selectApartmentVC.delegate = self;
            selectApartmentVC.canEdit = NO;
            selectApartmentVC.building = currentBuilding;
            
            selectApartmentVC.ownApartment = currentApartment;
            [self.navigationController pushViewController:selectApartmentVC animated:YES];
        }else{
            NSString *buildingShowName = [YWLoginTool buildingShowName];
            [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"请先选择%@",buildingShowName?:@"楼盘"]];
        }
    }
}
#pragma mark - YWSelectBuildingTableViewControllerDelegate
-(void)popSelectedBuilding:(YWBuilding *)building{
    if (building && ![currentBuilding.buildingId isEqualToString:building.buildingId]) {
        currentBuilding = building;
        currentApartment = nil;
        [self.tableView reloadData];
    }
}
#pragma mark - YWSelectApartmentTableViewControllerDelegate
- (void)popSelectedApartment:(YWApartment *)apartment{
    if (apartment && currentApartment.apartmentId != apartment.apartmentId) {
        currentApartment = apartment;
        [self.tableView reloadData];
    }
}

- (void)clickRightBarButton:(id)sender{
    NSMutableArray * tempArray = [NSMutableArray array];
    NSMutableArray * bigArray = [NSMutableArray array];
    [self.selLocArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[YWBuilding class]]) {
            YWBuilding *building = (YWBuilding*)obj;
             if (currentApartment){
                if ([currentBuilding.buildingId isEqualToString:building.buildingId]) {
                    [tempArray addObject:obj];
                }
            }else{
                if ([currentBuilding.buildingId isEqualToString:building.buildingId]) {
                    [bigArray addObject:obj];
                }
            }
        }else if ([obj isKindOfClass:[YWApartment class]]){
            YWApartment *apartment = (YWApartment*)obj;
            if (currentApartment){
                if (currentApartment.apartmentId == apartment.apartmentId) {
                    [bigArray addObject:obj];
                }
            }else if (currentBuilding && !currentApartment){
                if ([apartment.buildingId isEqualToString:currentBuilding.buildingId]) {
                    [bigArray addObject:obj];
                }
            }
        }
    }];
    
    if (tempArray.count>0) {
        NSString *tip = @"您之前选的位置已包含现在的位置，确定选择更小的位置吗？";
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:tip preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertController animated:YES completion:nil];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.selLocArray removeObjectsInArray:tempArray];
            if (currentApartment){
                [self.selLocArray addObject:currentApartment];
            }else if (currentBuilding && !currentApartment){
                [self.selLocArray addObject:currentBuilding];
            }
            if ([self.delegate respondsToSelector:@selector(selectLocationArray:)]) {
                [self.delegate selectLocationArray:self.selLocArray];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }]];
    }else{
        [self.selLocArray removeObjectsInArray:bigArray];
        if (currentApartment){
            [self.selLocArray addObject:currentApartment];
        }else if (currentBuilding && !currentApartment){
            [self.selLocArray addObject:currentBuilding];
        }
        if (currentBuilding) {
            if ([self.delegate respondsToSelector:@selector(selectLocationArray:)]) {
                [self.delegate selectLocationArray:self.selLocArray];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [YWCommonTool showTextHUDWithContent:@"请选择位置等信息"];
        }
    }
}
@end
